﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using NewRetail.Application.Components.WeChat.Services;
using NewRetail.Application.Core;
using System.Threading.Tasks;
using System.IO;
using System.Text;
using Microsoft.Extensions.Logging;
using NewRetail.Application.Components.WeChat.Model;
using System;
using NewRetail.Application.Utility;
using System.Text.Json;

namespace NewRetail.Api.Controllers.WeChatControllers
{
    /// <summary>
    /// 用于处理微信网页授权的信息
    /// </summary>
    [NewRetailRoute("wechat-oauth2")]
    public class WeChatOAuth2Controller : BaseController
    {
        #region Field
        private readonly IWeChatOAuth2Service _weChatOAuth2Service;
        private readonly ILogger _logger;
        #endregion

        #region Constructor
        public WeChatOAuth2Controller(IWeChatOAuth2Service weChatOAuth2Service, ILogger<WeChatOAuth2Controller> logger)
        {
            _weChatOAuth2Service = weChatOAuth2Service;
            _logger = logger;
        }
        #endregion

        #region method

        #region VUE中使用微信授权并获取openid等信息。VUE中首先get请求 http://xxx/api/new-retail/wechat-oauth2/wxoauthurladdress?url=http://xxx.com  获取code,然后根据code请求接口获取openid

        #region 微信授权返回URL地址, 先调用此接口，然后根据code调下面getwxuserbycode接口
        // GET api/new-retail/wechat-oauth2/wxoauthurladdress?url=WdZbUJqcXM=
        /// <summary>
        /// 微信授权返回URL地址
        /// </summary>
        /// <param name="url">前端需要跳转的页面地址</param>
        /// <remarks>首先如果前端code没有那么没有授权，因此需要先调用此接口，然后前端返回跳转到此接口的结果url.之后有code那么根据code调用getwxuserbycode接口获取openid</remarks>
        /// <returns></returns>
        [HttpGet("wxoauthurladdress")]
        public ResponseEntity<string> GetWxOAuthUrlAddress(string url)
        {
            var retResult = new ResponseEntity<string>();
            try
            {
                if (!string.IsNullOrEmpty(url))
                {
                    var result = _weChatOAuth2Service.GetWeChatOAuthUrl(url);
                    if (!string.IsNullOrEmpty(result.Item2))
                        retResult.SetError(result.Item2, "400");
                    else
                        retResult.SetData(result.Item1);
                }
                else
                    retResult.SetError("重定向url不能为空！", "400");
            }
            catch(Exception e)
            {
                _logger.LogError(e.Message);
                retResult.SetError(e.Message, "500");
            }

            return retResult;
        }
        #endregion

        #region 根据code获取openid等信息
        /// <summary>
        /// 微信公众号引导页，获取openid等信息
        /// </summary>
        /// <returns>成功时，返回带有用户信息的URL并重定向</returns>
        // GET api/new-retail/wechat-oauth2/getwxuserbycode?code=xxxx&state=xx
        [HttpGet("getwxuserbycode")]
        public async Task<ResponseEntity<WeChatOAuth2UserInfoDto>> GetWxUserByCode(string code)
        {
            var queryString = Request.QueryString;
            var retResult = new ResponseEntity<WeChatOAuth2UserInfoDto>();
            try
            {
                var result = await _weChatOAuth2Service.GetWeChatUserByCode(queryString);
                if (!string.IsNullOrEmpty(result.Item2))
                    retResult.SetError(result.Item2, "400");
                else
                    retResult.SetData(result.Item1);
            }
            catch (Exception e)
            {
                _logger.LogError(e.Message);
                retResult.SetError(e.Message, "500");
            }

            return retResult;
        }
        #endregion

        #endregion

        #region 获取微信配置供前端JS-SDK调用使用
        /// <summary>
        /// 获取微信配置供前端JS-SDK调用使用
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        // GET api/new-retail/wechat-oauth2/getwechatconfig
        [HttpGet("getwechatconfig")]
        public async Task<ResponseEntity<WeChatConfigJsSdkInfoDto>> GetWechatConfig(string url)
        {
            var retResult = new ResponseEntity<WeChatConfigJsSdkInfoDto>();
            try
            {
                var result = await _weChatOAuth2Service.GetWechatConfigInfo(url);
                if (!string.IsNullOrEmpty(result.Item2))
                    retResult.SetError(result.Item2, "400");
                else
                    retResult.SetData(result.Item1);
            }
            catch (Exception e)
            {
                _logger.LogError(e.Message);
                retResult.SetError(e.Message, "500");
            }

            return retResult;
        }
        #endregion

        #endregion
    }
}
